/* USER CODE BEGIN Header */
/**
  ******************************************************************************
  * @file    adc.c
  * @brief   This file provides code for the configuration
  *          of the ADC instances.
  ******************************************************************************
  * @attention
  *
  * Copyright (c) 2025 STMicroelectronics.
  * All rights reserved.
  *
  * This software is licensed under terms that can be found in the LICENSE file
  * in the root directory of this software component.
  * If no LICENSE file comes with this software, it is provided AS-IS.
  *
  ******************************************************************************
  */
/* USER CODE END Header */
/* Includes ------------------------------------------------------------------*/
#include "adc.h"

/* USER CODE BEGIN 0 */

/* USER CODE END 0 */

ADC_HandleTypeDef hadc1;

/* ADC1 init function */
void MX_ADC1_Init(void)
{

  /* USER CODE BEGIN ADC1_Init 0 */

  /* USER CODE END ADC1_Init 0 */

  ADC_ChannelConfTypeDef sConfig = {0};

  /* USER CODE BEGIN ADC1_Init 1 */

  /* USER CODE END ADC1_Init 1 */

  /** Common config
  */
  hadc1.Instance = ADC1;
  hadc1.Init.ScanConvMode = ADC_SCAN_DISABLE;
  hadc1.Init.ContinuousConvMode = DISABLE;
  hadc1.Init.DiscontinuousConvMode = DISABLE;
  hadc1.Init.ExternalTrigConv = ADC_SOFTWARE_START;
  hadc1.Init.DataAlign = ADC_DATAALIGN_RIGHT;
  hadc1.Init.NbrOfConversion = 1;
  if (HAL_ADC_Init(&hadc1) != HAL_OK)
  {
    Error_Handler();
  }

  /** Configure Regular Channel
  */
  sConfig.Channel = ADC_CHANNEL_0;
  sConfig.Rank = ADC_REGULAR_RANK_1;
  sConfig.SamplingTime = ADC_SAMPLETIME_1CYCLE_5;
  if (HAL_ADC_ConfigChannel(&hadc1, &sConfig) != HAL_OK)
  {
    Error_Handler();
  }
  /* USER CODE BEGIN ADC1_Init 2 */

  /* USER CODE END ADC1_Init 2 */

}

void HAL_ADC_MspInit(ADC_HandleTypeDef* adcHandle)
{

  GPIO_InitTypeDef GPIO_InitStruct = {0};
  if(adcHandle->Instance==ADC1)
  {
  /* USER CODE BEGIN ADC1_MspInit 0 */

  /* USER CODE END ADC1_MspInit 0 */
    /* ADC1 clock enable */
    __HAL_RCC_ADC1_CLK_ENABLE();

    __HAL_RCC_GPIOA_CLK_ENABLE();
    /**ADC1 GPIO Configuration
    PA0-WKUP     ------> ADC1_IN0
    */
    GPIO_InitStruct.Pin = GPIO_PIN_0;
    GPIO_InitStruct.Mode = GPIO_MODE_ANALOG;
    HAL_GPIO_Init(GPIOA, &GPIO_InitStruct);

  /* USER CODE BEGIN ADC1_MspInit 1 */

  /* USER CODE END ADC1_MspInit 1 */
  }
}

void HAL_ADC_MspDeInit(ADC_HandleTypeDef* adcHandle)
{

  if(adcHandle->Instance==ADC1)
  {
  /* USER CODE BEGIN ADC1_MspDeInit 0 */

  /* USER CODE END ADC1_MspDeInit 0 */
    /* Peripheral clock disable */
    __HAL_RCC_ADC1_CLK_DISABLE();

    /**ADC1 GPIO Configuration
    PA0-WKUP     ------> ADC1_IN0
    */
    HAL_GPIO_DeInit(GPIOA, GPIO_PIN_0);

  /* USER CODE BEGIN ADC1_MspDeInit 1 */

  /* USER CODE END ADC1_MspDeInit 1 */
  }
}

/* USER CODE BEGIN 1 */

/**
 * @brief 读取ADC1指定通道的值（支持16个通道）
 * @param channel: 要读取的通道号 (0-15)
 * @retval uint16_t: ADC转换结果值，失败返回0xFFFF
 */
uint16_t ADC_Read_Channel(uint8_t channel)
{
    // 检查通道号是否有效
    if (channel > 15) {
        return 0xFFFF;
    }
    
    // 通道号到ADC_CHANNEL的映射数组
    static const uint32_t channel_map[16] = {
        ADC_CHANNEL_0,   // 0  - PA0
        ADC_CHANNEL_1,   // 1  - PA1
        ADC_CHANNEL_2,   // 2  - PA2
        ADC_CHANNEL_3,   // 3  - PA3
        ADC_CHANNEL_4,   // 4  - PA4
        ADC_CHANNEL_5,   // 5  - PA5
        ADC_CHANNEL_6,   // 6  - PA6
        ADC_CHANNEL_7,   // 7  - PA7
        ADC_CHANNEL_8,   // 8  - PB0
        ADC_CHANNEL_9,   // 9  - PB1
        ADC_CHANNEL_10,  // 10 - PC0
        ADC_CHANNEL_11,  // 11 - PC1
        ADC_CHANNEL_12,  // 12 - PC2
        ADC_CHANNEL_13,  // 13 - PC3
        ADC_CHANNEL_14,  // 14 - PC4
        ADC_CHANNEL_15   // 15 - PC5
    };
    
    // 临时修改为单通道模式
    hadc1.Init.ScanConvMode = ADC_SCAN_DISABLE;
    hadc1.Init.NbrOfConversion = 1;
    HAL_ADC_Init(&hadc1);
    
    ADC_ChannelConfTypeDef sConfig = {0};
    sConfig.Channel = channel_map[channel];
    sConfig.Rank = ADC_REGULAR_RANK_1;
    sConfig.SamplingTime = ADC_SAMPLETIME_239CYCLES_5;
    HAL_ADC_ConfigChannel(&hadc1, &sConfig);
    
    // 手动开启转换
    HAL_ADC_Start(&hadc1);
    
    // 等待转换完成
    uint16_t adc_value = 0xFFFF;
    if (HAL_ADC_PollForConversion(&hadc1, 1000) == HAL_OK) {
        adc_value = HAL_ADC_GetValue(&hadc1);
    }
    
    // 停止转换
    HAL_ADC_Stop(&hadc1);    
    return adc_value;
}

/**
 * @brief 计算累加和校验
 * @param data: 数据指针
 * @param length: 数据长度
 * @retval uint8_t: 累加和
 */
uint8_t ADC_Calculate_Checksum(uint8_t* data, uint8_t length)
{
    uint8_t checksum = 0;
    for (uint8_t i = 0; i < length; i++) {
        checksum += data[i];
    }
    return checksum;
}

/**
 * @brief 发送ADC协议数据包
 * @param channels: 要读取的通道数组
 * @param channel_count: 通道数量
 * @retval None
 */
void ADC_Send_Protocol_Data(uint8_t* channels, uint8_t channel_count)
{
    if (channel_count == 0 || channel_count > 16) {
        return;
    }
    
    // 计算数据包总长度
    // 帧头(2) + 命令字(1) + 通道数(1) + 数据(通道数*2) + 累加和(1) + 帧尾(2)
    uint8_t total_length = 2 + 1 + 1 + channel_count * 2 + 1 + 2;
    uint8_t protocol_data[64]; // 最大支持16个通道，数据包不会超过64字节
    uint8_t data_index = 0;
    
    // 1. 帧头
    protocol_data[data_index++] = 0xaa;  // 0xAA
    protocol_data[data_index++] = 0x55;  // 0x55
    
    // 2. 命令字
    protocol_data[data_index++] = 0x01;    // 0x01
    
    // 3. 通道数
    protocol_data[data_index++] = channel_count;
    
    // 4. 读取每个通道的ADC值并打包
    for (uint8_t i = 0; i < channel_count; i++) {
        uint16_t adc_value = ADC_Read_Channel(channels[i]);
        
        // 大端序：高8位在前，低8位在后
        protocol_data[data_index++] = (uint8_t)((adc_value >> 8) & 0xFF);  // 高8位
        protocol_data[data_index++] = (uint8_t)(adc_value & 0xFF);         // 低8位
    }
    
    // 5. 计算累加和（从命令字到最后一个数据字节）
    uint8_t checksum = ADC_Calculate_Checksum(&protocol_data[2], data_index - 2);
    protocol_data[data_index++] = checksum;
    
    // 6. 帧尾
    protocol_data[data_index++] = 0x0d;    // 0x0D
    protocol_data[data_index++] = 0x0a;    // 0x0A
    
    // 7. 通过UART发送完整数据包
    for (uint8_t i = 0; i < total_length; i++) {
        UART_SendByte(protocol_data[i]);
    }
}

/* USER CODE END 1 */
